<template>
  <div>
    <van-nav-bar
      title="商铺信息"
      left-text="返回"
      right-text="按钮"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <van-icon name="more" slot="left" size="1.4em" />
      <van-icon name="edit" slot="right" size="1.4em" />
    </van-nav-bar>
    <van-cell-group>
      <!-- <van-cell title="商铺信息">
      </van-cell>-->
      <van-field
        left-icon="shop"
        label="商户名称"
        :readonly="!editable"
        v-model="shopInfo.shopName"
        placeholder="请输入商户名"
        center
        clearable
      />
      <van-field
        left-icon="username"
        label="负责人"
        :readonly="!editable"
        v-model="shopInfo.managerName"
        placeholder="请输入负责人"
        center
        clearable
      />
      <van-field
        left-icon="mobile"
        label="手机"
        :readonly="!editable"
        v-model="shopInfo.managerMobile"
        placeholder="请输入手机"
        center
        clearable
      />
      <van-field
        left-icon="address"
        label="地址"
        :readonly="!editable"
        v-model="shopInfo.addr"
        placeholder="请输入地址"
        center
        clearable
        type="textarea"
        autosize="true"
      />
      <van-cell icon="liability" title="责任书">
        <template slot="right-icon">
          <van-icon
            v-if="shopInfo.dutyLetter&&!editable"
            name="browsing-history"
            color="green"
            size="1.4em"
            class="van-cell__right-icon"
            @click="viewPic"
          />
          <van-icon
            v-else
            name="camera"
            color="red"
            size="1.4em"
            class="van-cell__right-icon"
            @click="takePic"
          />
        </template>
      </van-cell>
      <van-cell icon="shoppic" title="店铺照片">
        <template slot="right-icon">
          <van-icon
            v-if="shopInfo.picture"
            name="browsing-history"
            color="green"
            size="1.4em"
            class="van-cell__right-icon"
            @click="viewShopPic"
          />
          <van-icon
            v-else
            name="camera"
            color="red"
            size="1.4em"
            class="van-cell__right-icon"
            @click="takeShopPic"
          />
        </template>
      </van-cell>
      <van-cell
        icon="location"
        title="定位"
        :value="shopInfo.lat?'已定位':'未定位'"
        is-link
        :to="{ path: 'location',name:'location', query: shopInfo}"
      />
      <van-cell
        icon="smoke-sensor2"
        title="设备"
        :value="deviceCount"
        is-link
        :arrow-direction="devicesCollapsed?'right':'down'"
        @click="toggleCollapse"
      />
    </van-cell-group>
    <div>
      <van-swipe-cell
        :right-width="delWidth"
        :on-close="onClose"
        v-for="(item, index) in items"
        :key="index"
        :imei="item.imei"
        v-show="!devicesCollapsed"
      >
        <van-cell-group :border="true">
          <van-cell :value="item.imei" icon="smoke-sensor2">
            <template slot="title">
              <span class="van-cell-text">{{item.devName}}</span>
              <van-tag type="danger">{{item.devModel}}</van-tag>
            </template>
            <template slot="right-icon">
              <van-icon
                v-if="item.installPic&&!editable"
                name="browsing-history"
                color="green"
                size="1.4em"
                class="van-cell__right-icon"
                @click="viewInstallPic(item.installPic)"
              />
              <van-icon
                v-else
                name="camera"
                color="red"
                size="1.4em"
                class="van-cell__right-icon"
                @click="takeInstallPic(item.imei)"
              />
            </template>
          </van-cell>
        </van-cell-group>
        <van-button
          slot="right"
          class="van-swipe-cell__right"
          :style="{'width':delWidth+'px'}"
          tag="div"
          @click="unBindDevice(item.imei)"
        >解绑</van-button>
      </van-swipe-cell>
    </div>
    <div class="operaiton-button" v-show="editable">
      <van-button size="large" type="danger" :loading="isLoading" @click="submiteSave">确认修改</van-button>
    </div>
    <transition name="fade">
      <div class="function-panel" v-show="functionPanelShow">
        <div class="triangle-up"></div>
        <div class="van-cell van-cell--center function-item" @click="sanQRCode">
          <i class="van-icon van-icon-qr van-cell__left-icon"></i>
          <div class="van-cell__title">
            <span>二维码绑定设备</span>
          </div>
        </div>
        <div class="van-cell van-cell--center function-item" @click="addDevice">
          <i class="van-icon van-icon-add van-cell__left-icon"></i>
          <div class="van-cell__title">
            <span>手动添加设备</span>
          </div>
        </div>
      </div>
    </transition>

    <van-popup v-model="addDeviceShow" position="top" :overlay="true">
      <div style="padding:10px 30px 20px">
        <div style="text-align:center;font-size:18px;padding:10px;">绑定设备</div>
        <van-cell-group>
          <van-field
            v-model="deviceForm.imei"
            required
            clearable
            left-icon="imei"
            label="IMEI"
            placeholder="请输入IMEI号"
            :error-message="errorMsg.imei"
          />
          <van-field
            v-model="deviceForm.iccid"
            required
            clearable
            left-icon="iccid"
            label="ICCID"
            placeholder="请输入ICCID"
            :error-message="errorMsg.imei"
          />
          <van-field
            v-model="deviceForm.installAddr"
            required
            clearable
            left-icon="address"
            label="安装地址"
            placeholder="请输安装地址"
            :error-message="errorMsg.installAddr"
          />
        </van-cell-group>
        <van-button size="large" type="danger" :loading="isLoading" @click="submitBindDevice">提交绑定</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import {
  getShopInfo,
  saveShop,
  getDevices,
  bindDevice,
  unBindDevice,
  uploadDutyLetter,
  uploadPicture,
  uploadShopPicture
} from "./../../api/building";
import validator from "@/libs/validator";
import { mediaURL } from "@/config";
export default {
  data() {
    return {
      shopId: 0,
      shopInfo: {
        shopId: 0,
        addr: "光谷金融港",
        dutyLetter: null,
        managerMobile: "18627771160",
        managerName: "刘恒",
        shopName: "飞发走丝",
        alarmNotifier: ""
      },
      isLoading: false,
      editable: false,
      functionPanelShow: false,
      addDeviceShow: false,
      devicesCollapsed: true,
      deviceCount: 0,
      items: [],
      deviceForm: {
        imei: "",
        iccid: "",
        installAddr: ""
      },
      errorMsg: {
        imei: "",
        installAddr: ""
      },
      rules: {
        imei: [{ required: true, message: "请输入imei号" }],
        installAddr: [{ required: true, message: "请输入安装地址" }]
      }
    };
  },
  computed: {
    delWidth() {
      return window.innerWidth * 0.2;
    }
  },
  watch: {},
  created() {
    this.validator = validator(this.rules, this.deviceForm);
  },
  mounted() {
    this.shopId = this.$route.query.shopId;
    this.getShopInfo();
    this.getDevices();
  },
  activated() {},
  deactivated() {},
  methods: {
    async getShopInfo() {
      let res = await getShopInfo({ id: this.shopId });
      if (res.code === 0) {
        this.shopInfo = res.data;
      } else {
        this.$toast.fail(res.msg);
      }
    },
    async submiteSave() {
      this.isLoading = true;
      let res = await saveShop(this.shopInfo);
      if (res.code === 0) {
        this.editable = false;
        this.$toast.success("修改成功");
      } else {
        this.$toast.fail(res.msg);
      }
      this.isLoading = false;
    },
    onClickLeft() {
      this.functionPanelShow = !this.functionPanelShow;
    },
    onClickRight() {
      this.editable = true;
    },
    toggleCollapse() {
      this.devicesCollapsed = !this.devicesCollapsed;
    },
    async getDevices() {
      let res = await getDevices({ id: this.shopId });
      if (res.code === 0) {
        this.deviceCount = res.data.total;
        this.items = res.data.records;
      } else {
        this.$toast.fail(res.msg);
      }
    },
    onClose(clickPosition, instance) {
      const vm = this;
      console.log(this);
      const IMEI = instance.$attrs.imei;
      switch (clickPosition) {
        case "left":
        case "cell":
        case "outside":
          instance.close();
          break;
        case "right":
          this.$dialog
            .confirm({
              message: "确定解绑？"
            })
            .then(() => {
              vm.submitUnBindDevice(IMEI);
              instance.close();
            })
            .catch(() => {
              // on cancel
            });
          break;
      }
    },
    sanQRCode() {
      this.functionPanelShow = false;
      this.deviceForm.installAddr = "";
      this.resetField();
      const vm = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function(res) {
          try {
            let result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
            let IMEI = "";
            let ICCID = "";
            if (result.indexOf("=") > -1) {
              let arr = result.split("&");

              if (arr.length == 2) {
                IMEI = arr[0].split("=")[1];
                ICCID = arr[1].split("=")[1];
              }
              if ((arr.length = 1)) {
                IMEI = arr[0].split("=")[1];
              }
            } else if (result.indexOf("NB_") > -1) {
              IMEI = result;
              ICCID = result;
            } else if (result.indexOf(",") > -1) {
              IMEI = result.split(",")[1];
              ICCID = result.split(",")[1];
            }

            if (IMEI) {
              vm.deviceForm.imei = IMEI;
              vm.deviceForm.iccid = ICCID;
              vm.deviceForm.installAddr = vm.shopInfo.addr;
              vm.addDeviceShow = true;
            } else {
              vm.$toast("请扫描烟感设备二维码");
            }
          } catch (error) {
            vm.$toast("请扫描烟感设备二维码");
          }
        }
      });
    },
    /**
     * 验证方法
     * @param callback
     * @param data
     */
    validate(callback, data) {
      this.validator.validate((errors, fields) => {
        this.resetField();
        if (errors) {
          fields.forEach(item => {
            this.errorMsg[item.field] = item.message;
          });
        }
        callback && callback(errors, fields);
      }, data);
    },
    /**
     * 清除验证提示
     * @param attrs
     */
    resetField(attrs) {
      attrs = !attrs
        ? Object.keys(this.errorMsg)
        : Array.isArray(attrs)
        ? attrs
        : [attrs];
      attrs.forEach(attr => {
        this.errorMsg[attr] = "";
      });
    },
    addDevice() {
      this.functionPanelShow = false;
      this.deviceForm.imei = "";
      this.deviceForm.installAddr = this.shopInfo.addr;
      this.resetField();
      this.addDeviceShow = true;
    },
    async submitBindDevice() {
      this.isLoading = true;
      this.validate(async (errors, fields) => {
        if (!errors) {
          let res = await bindDevice({
            imei: this.deviceForm.imei,
            iccid: this.deviceForm.iccid,
            installAddr: this.deviceForm.installAddr,
            shopId: this.shopId
          });
          if (res.code === 0) {
            this.addDeviceShow = false;
            this.$toast.success("设备绑定成功！");
            this.getDevices();
          } else {
            this.$toast.fail(res.msg);
          }
        }
      });

      this.isLoading = false;
    },
    async submitUnBindDevice(IMEI) {
      let res = await unBindDevice({ imei: IMEI });
      if (res.code === 0) {
        this.$toast.success("设备解绑成功！");
        this.getDevices();
      } else {
        this.$toast.fail(res.msg);
      }
    },
    takePic() {
      const vm = this;
      wx.chooseImage({
        count: 1, //张数， 默认9
        sizeType: ["compressed"], //建议压缩图
        sourceType: ["album", "camera"], // 来源是相册、相机
        success: function(res) {
          // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          var localId = res.localIds[0];
          wx.uploadImage({
            localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function(res) {
              var serverId = res.serverId; // 返回图片的服务器端ID
              vm.useNowLocation(serverId);
            }
          });
        }
      });
    },
    //店铺照片
    takeShopPic() {
      const vm = this;
      wx.chooseImage({
        count: 1, //张数， 默认9
        sizeType: ["compressed"], //建议压缩图
        sourceType: ["album", "camera"], // 来源是相册、相机
        success: function(res) {
          // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          var localId = res.localIds[0];
          wx.uploadImage({
            localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function(res) {
              var serverId = res.serverId; // 返回图片的服务器端ID
              vm.useShopNowLocation(serverId);
            }
          });
        }
      });
    },
    useShopNowLocation(serverId) {
      const vm = this;
      wx.getLocation({
        type: "gcj02",
        success: function(res) {
          vm.uploadShopPic(serverId, res.latitude, res.longitude);
        },
        cancel: function(res) {
          //this.$toast.success('用户拒绝授权获取地理位置');
        }
      });
    },
    useNowLocation(serverId) {
      const vm = this;
      wx.getLocation({
        type: "gcj02",
        success: function(res) {
          vm.uploadPic(serverId, res.latitude, res.longitude);
        },
        cancel: function(res) {
          //this.$toast.success('用户拒绝授权获取地理位置');
        }
      });
    },
    async uploadPic(serverId, lat, lng) {
      let res = await uploadDutyLetter({
        media_id: serverId,
        id: this.shopInfo.shopId,
        lat: lat,
        lng: lng
      });
      if (res.code === 0) {
        this.shopInfo.dutyLetter = res.data;
        this.$toast.success("上传成功！");
      } else {
        this.$toast.fail("上传失败！");
      }
    },
    async uploadShopPic(serverId, lat, lng) {
      let res = await uploadShopPicture({
        media_id: serverId,
        id: this.shopInfo.shopId,
        lat: lat,
        lng: lng
      });
      if (res.code === 0) {
        this.shopInfo.picture = res.data;
        this.$toast.success("上传成功！");
      } else {
        this.$toast.fail("上传失败！");
      }
    },
    viewPic() {
      const devicePicPath = mediaURL + this.shopInfo.dutyLetter;
      wx.previewImage({
        current: "", // 当前显示图片的http链接
        urls: [devicePicPath] // 需要预览的图片http链接列表
      });
    },
    viewShopPic() {
      const devicePicPath = mediaURL + this.shopInfo.picture;
      wx.previewImage({
        current: "", // 当前显示图片的http链接
        urls: [devicePicPath] // 需要预览的图片http链接列表
      });
    },
    installUseNowLocation(serverId, imei) {
      const vm = this;
      wx.getLocation({
        type: "gcj02",
        success: function(res) {
          vm.uploadInstallPic(serverId, imei, res.latitude, res.longitude);
        },
        cancel: function(res) {
          //this.$toast.success('用户拒绝授权获取地理位置');
        }
      });
    },
    takeInstallPic(imei) {
      const vm = this;
      wx.chooseImage({
        count: 1, //张数， 默认9
        sizeType: ["compressed"], //建议压缩图
        sourceType: ["album", "camera"], // 来源是相册、相机
        success: function(res) {
          // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          var localId = res.localIds[0];
          wx.uploadImage({
            localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function(res) {
              var serverId = res.serverId; // 返回图片的服务器端ID
              vm.installUseNowLocation(serverId, imei);
            }
          });
        }
      });
    },
    async uploadInstallPic(serverId, imei, lat, lng) {
      let res = await uploadPicture({
        media_id: serverId,
        imei: imei,
        lat: lat,
        lng: lng
      });
      if (res.code === 0) {
        this.getDevices();
        this.$toast.success("上传成功！");
      } else {
        this.$toast.fail("上传失败！");
      }
    },
    viewInstallPic(installPic) {
      const installPicPath = mediaURL + installPic;
      wx.previewImage({
        current: "", // 当前显示图片的http链接
        urls: [installPicPath] // 需要预览的图片http链接列表
      });
    }
  }
};
</script>


<style lang="scss" scoped>
@import "./../../../../assets/scss/mixin";
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}
.van-cell__value {
  padding-right: 22px;
}
.sub-wrapper {
  display: flex;
  margin-top: 10px;
  padding: 20px;
  background-color: #fff;
  .sub-item {
    flex: 1;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40vw;
    border: 1px solid #eee;
  }
}
.van-swipe-cell {
  &__left,
  &__right {
    color: #ffffff;
    font-size: 14px;
    height: 100%;
    display: inline-block;
    text-align: center;
    display: flex;
    align-items: center; /*垂直居中*/
    justify-content: center; /*水平居中*/
    background-color: #f44;
  }
}
.function-panel {
  width: 160px;
  position: absolute;
  top: 45px;
  z-index: 9999;
  .triangle-up:before {
    content: "";
    position: absolute;
    top: -20px;
    left: 14px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid #666;
    border-right: 10px solid transparent;
    border-left: 10px solid transparent;
  }
  .function-item {
    color: #fff;
    display: flex;
    align-items: center;
    background-color: #666;
  }
  &:activated {
    background-color: #e8e8e8;
  }
}
</style>
